<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/GPL-3.0
 * @link https://www.gougucms.com
 */

declare (strict_types = 1);

namespace app\base;

use think\App;
use think\exception\HttpResponseException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;
use systematic\Systematic;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;
protected $param=[];
    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];
    /**
     * @var array
     * 部门及下级部门id
     */
    protected $dSons=[];
    protected $authList=[];
    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app = $app;
        $this->request = $this->app->request;
        $this->module = strtolower(app('http')->getName());
        $this->controller = strtolower($this->request->controller());
        $this->action = strtolower($this->request->action());
        $this->uid = 0;
        $this->loginInfo=[];
        $this->did = 0;
        $this->pid = 0;
        $this->param=$this->request->param();
        // 控制器初始化
        $this->initialize();
    }
    // 初始化
    protected function initialize()
    {
        // 检测权限
        $this->checkLogin();
    }

    /**
     *验证用户登录
     */
    protected function checkLogin()
    {
        if ($this->controller !== 'login' && $this->controller !== 'captcha') {
            $session_admin = get_config('app.session_admin');
            if (!Session::has($session_admin)) {
                if ($this->request->isAjax()) {
                    return to_assign(404, '请先登录');
                } else {
                    redirect('/home/login/index.html')->send();
                    exit;
                }
            } else {
                $this->uid = Session::get($session_admin);
				$login_admin = Db::name('Admin')->where(['id' => $this->uid])->find();
				$this->did = $login_admin['did'];
				$this->pid = $login_admin['position_id'];
				$this->loginInfo=$login_admin;
                $dSonIds=$this->getAllSubIds($this->did,'department');
                $dSonIds[]=$login_admin['did'];
                $this->dSons=$dSonIds;
                View::assign('login_admin', $login_admin);				
				$is_lock = $login_admin['is_lock'];
				if($is_lock==1){
					redirect('/home/login/lock.html')->send();
					exit;
				}
                // 验证用户访问权限
                if (($this->module == 'api') || ($this->module == 'message') || ($this->module == 'home' && $this->controller == 'index')) {
					return true;
				}
				else{
					$reg_pwd = $login_admin['reg_pwd'];
					if($reg_pwd!==''){
						redirect('/home/index/edit_password.html')->send();
						exit;
					}
                    if (!$this->checkAuth()) {
                        if ($this->request->isAjax()) {
                            return to_assign(405, '你没有权限,请联系管理员或者HR');
                        } else {
                            echo '<div style="text-align:center;color:red;margin-top:20%;">你没有权限访问，请联系管理员或者人事部</div>';exit;
                        }
                    }
                }
            }
        }
    }

    /**
     * 验证用户访问权限
     * @DateTime 2020-12-21
     * @param    string $controller 当前访问控制器
     * @param    string $action 当前访问方法
     * @return   [type]
     */
    protected function checkAuth()
    {

		$uid = $this->uid;
		Cache::delete('RulesSrc' . $uid);
		$GOUGU = new Systematic();
        $GOUGU->auth($uid);

		$auth_list_all = Cache::get('RulesSrc0');
        $auth_list = Cache::get('RulesSrc' . $uid);
        $this->authList=$auth_list;
        $pathUrl = $this->module . '/' . $this->controller . '/' . $this->action;
        if ($uid==1||$uid==2){
            return true;
        }
//        halt(['aa'=>$auth_list,'bb'=>$pathUrl]);
        if (!in_array($pathUrl, $auth_list)) {
            return false;
        } else {
            return true;
        }
    }

    public function isHaveAuth($au='')
    {
        $uid=$this->uid;
        $pathUrl = $this->module . '/' . $this->controller .'/'.$au;
//        if ($uid==1){
//            return true;
//        }
        if (!in_array($pathUrl, $this->authList)) {
            return false;
        } else {
            return true;
        }
}
    /**
     * 实体还原，多用于前端接口
     */
     public  function htmlDecode($string, $border = false): string
    {
        $temp = html_entity_decode($string);
        $temp = self::filterXss($temp);
        if ($border === true) {
            $temp = '<div class="kuang">' . $temp . '</div>';
        }
        return $temp;
    }

    /**
     * 过滤xss
     *
     * @param string $html
     * @return string
     */
    public  function filterXss(string $html): string
    {
        $searchs  = [
            '<',
            '>',
        ];
        $replaces = [
            '&lt;',
            '&gt;',
        ];
        preg_match_all("/<([^<]+)>/i", $html, $matches);
        if ($matches[1]) {
            $whiteTags  = 'img|a|font|div|table|tbody|caption|tr|td|th|br|p|b|strong|i|u|em|span|ol|ul|li|blockquote';
            $matches[1] = array_unique($matches[1]);
            foreach ($matches[1] as $value) {
                $searchs[]  = "&lt;" . $value . "&gt;";
                $value      = str_replace(['\\', '/*'], ['.', '/.'], $value);
                $filterTags = [
                    'onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate',
                    'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange',
                    'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick',
                    'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate',
                    'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete',
                    'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel',
                    'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart',
                    'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop',
                    'onsubmit', 'onunload', 'javascript', 'script', 'eval', 'behaviour', 'expression', 'style', 'class',
                ];
                $filterStr  = implode('|', $filterTags);
                $value      = preg_replace(array("/($filterStr)/i"), '.', $value);

                if (!preg_match("/^[\/|\s]?($whiteTags)(\s+|$)/is", $value)) {
                    $value = '';
                }
                $replaces[] = empty($value) ? '' : "<" . str_replace('&quot;', '"', $value) . ">";
            }
        }
        return str_replace($searchs, $replaces, $html);
    }

    /**
     * @param $pid
     * @return array
     * date:2024/5/10
     * 所有下级分类
     */
    public function getAllSubIds($pid,$table='material_type',$pk='pid',$k='id') {
//        $subIds = Db::name('material_type')->where('pid', $pid)->column('id');
//        foreach ($subIds as $id) {
//            $subSubIds =$this-> getAllSubIds($id); // 递归调用
//            if (!empty($subSubIds)) {
//                $subIds = array_merge($subIds, $subSubIds);
//            }
//        }
//$sql="SELECT id FROM( SELECT id,pid FROM fy_material_type ORDER BY pid, id)org_query,(SELECT @id := {$pid}) initialisation WHERE FIND_IN_SET(pid,@id)>0 AND @id := CONCAT(@id,',',id)";
$sql="SELECT id FROM( SELECT {$k},{$pk} FROM fy_{$table} ORDER BY {$pk}, {$k})org_query,(SELECT @id := {$pid}) initialisation WHERE FIND_IN_SET({$pk},@id)>0 AND @id := CONCAT(@id,',',{$k})";
       $data=Db::query($sql);
       $subIds=[];
       foreach ($data as $v){
           $subIds[]=$v['id'];
       }
        return $subIds;
    }

    /**
     * @param string $table
     * @param string $field
     * @return false|string
     * date:2024/7/3
     * 获取打印编号
     */
    public function getDJBHBuySql($table='',$field='orderNum',$text='')
    {

        try {
            $code=Db::name($table)
                ->where('status','>',-1)
                ->where($field,'like',$text.date('Ym').'%')
                ->order("{$field} DESC")
                ->value($field);

        }catch (\Exception $exception){
            $code='';
        }
        if ($code){
            $code=str_replace($text,'',$code);
            $code=(int)$code+1;
        }else{
            $num=0;
            if ($num){
                $num+=1;
            }else{
                $num=1;
            }
            $str=(string)(1000+$num);
            $code=substr($str, 1);
            $code=date('Ym').$code;
        }
        return $text.$code;
    }

}
